<script lang="ts" setup name="planEdit">
import { useRoute, useRouter } from "vue-router";
import { onMounted, ref, watch } from "vue";
// import { getYMD } from "@/utils/date";
import ProTable from "@/components/ProTable/index.vue";
import SelectTreeTable from "@/components/SelectTreeData/index.vue";
import {
  getWaresCategoryList,
  getInventoryGoodsList,
  getStorehouseList,
  getStockPlanEdit,
  createStockPlan,
  editStockPlan
  // checkStockPlan
} from "@/api/modules/inventory";
import { ElMessage } from "element-plus";
// import { MoreFilled } from "@element-plus/icons-vue"; 小图标 ...
// import type { FormInstance } from "element-plus";  定义rules和一写表单小图标表单大小

// const ruleFormRef = ref<FormInstance>();
const router = useRouter();
const route = useRoute();

const typeScopeList: stockSPlanStatus = [
  { label: "单品盘点", value: 1 },
  { label: "全场盘点", value: 2 }
];
/* 仓库start */
const storeList = ref<any[]>([]);
// const defaultHouserId = ref(null);
const onShowStore = async () => {
  const res = await getStorehouseList();
  storeList.value = res.data.list;
  storeList.value.forEach(v => {
    if (v.isDefault) {
      stockPlanForm.value.houseId = v.id;
    }
  });
};
const selectChange = () => {
  stockPlanForm.value.inventoryplandetailList = [];
};

watch();
// 主数据，发请求和渲染截面数据
const stockPlanForm = ref({
  orderId: 0,
  orderNo: "",
  // corpId: 0,
  // storeId: 0,
  planType: 1,
  status: 1,
  sysUserId: 0,
  // checkerId: 0,
  checkFlag: 1,
  // checkTime: 0,
  // updateTime: 0,
  houseId: 0,
  // createTime: getYMD(),
  remark: "",
  inventoryplandetailList: []
});
// inventory: {
//   inventorydetailList: []
// }

const houseIdF = ref(null); // 如果是编辑复原仓库是复原数据
const newList = ref([]);
watch(
  () => stockPlanForm.value.houseId,
  () => {
    if (houseIdF.value === stockPlanForm.value.houseId && route.query.id) {
      stockPlanForm.value.inventoryplandetailList = newList.value;
    }
  }
);

const proTable = ref();
// 外层表格的列的每一项
const columns: ColumnProps<Inventory.ResPurchaseList>[] = [
  { type: "index", label: "序号", width: 60 },
  { prop: "operate", label: "操作", width: 100 },
  { prop: "barcode", label: "编码", minWidth: 220 },
  { prop: "name", label: "名称", minWidth: 140 },
  { prop: "categoryName", label: "分类名称", minWidth: 140 },
  { prop: "productName", label: "规格", minWidth: 100 },
  { prop: "quantity", label: "账面数量", minWidth: 120 },
  { prop: "price", label: "成本价", minWidth: 120 },
  { prop: "unitName", label: "单位", minWidth: 120 }
];

// 打开库存商品弹出层列表
const selectTreeTableRef = ref<InstanceType<typeof SelectTreeTable> | null>(null);
const openSelectTreeTable = (title: string, searchVal: string | number) => {
  if (!stockPlanForm.value.houseId) return ElMessage.error("请先选择仓库");
  const params = {
    title,
    isView: false,
    searchVal,
    index: 0,
    mate: "productsId",
    selTags: stockPlanForm.value.inventoryplandetailList
      .filter(age => age.goodsId !== 0)
      .map(i => {
        i.name = i.name;
        i.id = i.productsId;
        return i;
      }),
    columns: [
      { type: "selection", width: 80 },
      { prop: "barcode", label: "编码", align: "left", minWidth: 220 },
      { prop: "name", label: "商品名称", align: "left", minWidth: 220 },
      { prop: "productName", label: "规格", align: "left", minWidth: 100 },
      { prop: "unitName", label: "单位", align: "left", minWidth: 100 },
      // { prop: "posPrice", label: "商品价格", minWidth: 120 }
      { prop: "purPrice ", label: "采购价格", minWidth: 120 }
    ],
    apiParams: { houseId: stockPlanForm.value.houseId },
    idName: "goodsCategoryId",
    // 发请求
    treeApi: getWaresCategoryList,
    api: getInventoryGoodsList
  };
  selectTreeTableRef.value?.acceptParams(params);
};
// 选中库存商品
const handleSelectedTreeList = (val: any) => {
  if (val.list.length > 0) {
    let list = val.list.map(im => {
      return {
        name: im.name,
        id: im.id,
        storeId: im.storeId,
        corpId: im.corpId,
        productsId: im.productsId,
        productName: im.productName,
        goodsId: im.id,
        quantity: im.planQuantity,
        price: im.costPrice,
        barcode: im.barcode,
        unitName: im.unitName,
        categoryName: im.categoryName
      };
      // {
      //   goodsName: im.name,
      //   goodsId: im.id,
      //   products: im.productName,
      //   productsId: im.productId,
      //   productName: im.productName,
      //   quantity: 1,
      //   barcode: im.barcode,
      //   price: im.posPrice,
      //   amount: im.posPrice,
      //   taxRate: 0,
      //   isGift: false,
      //   giftQuantity: 0,
      //   convert: im.convert
      // };
    });

    list.forEach(v => {
      if (!stockPlanForm.value.inventoryplandetailList.some(i => i.productsId === v.productsId)) {
        stockPlanForm.value.inventoryplandetailList.push(v);
      }
    });
  }
};
const delSpecRow = (index: number) => {
  if (stockPlanForm.value.inventoryplandetailList.length <= 1) return ElMessage.error("商品不能少于一条数据");
  stockPlanForm.value.inventoryplandetailList.splice(index, 1);
};

// 数据已审核需要渲染详情
const inventory = ref([]);
// const all = ref([]);
// const flat = ref([]);
// const profit = ref([]);
// const omit = ref([]);

const stockDetailList = ref([
  { label: "全部", list: [], name: "first" },
  { label: "盘平", list: [], name: "second" },
  { label: "盘盈", list: [], name: "third" },
  { label: "盘亏", list: [], name: "fourth" }
]);

// 😒😒😒😒😒😒判断数据回来是否是可查看还是可编辑，查看禁用不能操作
const documentStatus: string = ref("add");
onMounted(async () => {
  onShowStore();
  if (route.query?.id) {
    const res = await getStockPlanEdit({ id: route.query.id });
    stockPlanForm.value = JSON.parse(JSON.stringify(res.data));
    houseIdF.value = res.data.houseId;
    newList.value = res.data.inventoryplandetailList;
    // console.log(res);
    if (res.data.inventory) {
      inventory.value = [{ ...JSON.parse(JSON.stringify(res.data.inventory)) }];

      stockDetailList.value[0].list = JSON.parse(JSON.stringify(res.data.inventory.inventorydetailList));
      res.data.inventory.inventorydetailList.forEach(v => {
        if (v.detailType === -1) {
          stockDetailList.value[3]?.list.push(v);
        } else if (v.detailType === 1) {
          console.log(44444);
          stockDetailList.value[2]?.list.push(v);
        } else {
          console.log(5555);
          stockDetailList.value[1]?.list.push(v);
        }
      });
    }

    if (res.data.status !== 1) {
      // 编辑
      documentStatus.value = "audited";
    } else {
      // 查看
      documentStatus.value = "edit";
    }
  } else {
    documentStatus.value = "add";
  }
});

// 盘点明细
const activeName = ref("first");

const onSubmit = async () => {
  if (stockPlanForm.value.inventoryplandetailList < 1) return ElMessage.error("商品明细不能为空");
  if (route.query.id) {
    await editStockPlan(stockPlanForm.value);
    router.push({
      path: "/stock/stockPlanList",
      query: {
        upList: true
      }
    });
  } else {
    await createStockPlan(stockPlanForm.value);
    router.push({
      path: "/stock/stockPlanList",
      query: {
        upList: true
      }
    });
  }
};

// const onCheckSubmit = () => {
//   if (stockPlanForm.value.inventoryplandetailList < 1) return ElMessage("商品明细不能为空");
//   await checkStockPlan(stockPlanForm.value);
//   router.push({
//     path: "/stock/stockPlanList",
//     query: {
//       upList: true
//     }
//   });
// };
</script>

<template>
  <div class="table-box card">
    <div class="ed-head">
      <span class="title">{{ documentStatus === "edit" ? "修改" : documentStatus === "add" ? "新增" : "" }}盘点计划</span>
      <el-icon class="pointer" @click="router.go(-1)"><CloseBold /></el-icon>
    </div>
    <el-form :model="stockPlanForm" label-width="120px" :rules="planRules" ref="ruleFormRef" :inline="true">
      <el-form-item label="单据号" prop="orderNo">
        <el-input class="width160" v-model="stockPlanForm.orderNo" disabled placeholder="系统自动生成" />
      </el-form-item>
      <el-form-item label="盘点范围" prop="planType">
        <el-select class="width150" v-model="stockPlanForm.planType" :disabled="documentStatus === 'audited'">
          <el-option v-for="item in typeScopeList" :label="item.label" :value="item.value" :key="item.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="盘点日期日期" prop="createTime">
        <el-date-picker class="width150" v-model="stockPlanForm.createTime" type="date" value-format="YYYY-MM-DD" />
      </el-form-item> -->

      <el-form-item label="仓库" prop="houseId">
        <el-select
          class="width150"
          :disabled="documentStatus === 'audited'"
          @change="selectChange"
          v-model="stockPlanForm.houseId"
        >
          <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input class="width150" v-model="stockPlanForm.remark" placeholder="请填写" :rows="1" type="textarea" />
      </el-form-item>
    </el-form>
    <!-- tool-button:自定头部右侧的按钮 -->
    <div style="min-height: 30%">
      <ProTable
        ref="proTable"
        row-key="id"
        :columns="columns"
        :data="stockPlanForm.inventoryplandetailList"
        :pagination="false"
        :is-card="false"
        :tool-button="documentStatus !== 'audited'"
      >
        <template #tableHeader>
          <el-button v-if="documentStatus !== 'audited'" type="primary" @click="openSelectTreeTable('选择商品')">
            添加商品明细
          </el-button>
        </template>
        <template #toolButton>
          <!-- 盘点计划没有审核，盘点单里面可以获取到盘点计划的进行盘点 -->
          <!-- <el-button v-if="stockPlanForm.status === 1 || documentStatus === 'add'" type="primary" @click="onCheckSubmit">
          保存并审核
        </el-button> -->
          <el-button v-if="documentStatus !== 'audited'" @click="onSubmit" type="primary"> 保存 </el-button>
          <el-button v-if="stockPlanForm.status === 3" @click="onSubmit" type="primary"> 审核 </el-button>
          <el-button @click="router.go(-1)"> 返回 </el-button>
        </template>

        <template #operate="scope">
          <div class="flx-justify-between" v-if="documentStatus !== 'audited'">
            <el-icon size="18" color="#169D82" @click="openSelectTreeTable('选择商品')"><Plus /></el-icon>
            <el-icon @click="delSpecRow(scope.$index)" size="18" color="#f00"><Minus /></el-icon>
          </div>
          <div v-else>--</div>
        </template>
      </ProTable>
    </div>

    <SelectTreeTable ref="selectTreeTableRef" @selected-list="handleSelectedTreeList"></SelectTreeTable>

    <!-- 盘点明细 -->
    <div v-if="documentStatus === 'audited'">
      <div style="padding: 20px 20px 0; color: #fdc31d">盘点单据</div>
      <hr style="border: 1px solid #e4e7ed" />

      <el-table border :data="inventory" style="width: 100%; height: 30%">
        <el-table-column align="center" prop="orderNo" label="单据号" width="250" />
        <el-table-column align="center" prop="checkFlagName" label="状态" width="250"> </el-table-column>
        <el-table-column align="center" prop="sysUserId" label="制单人" />
        <el-table-column align="center" prop="createTime" label="制单日期" />
        <el-table-column align="center" prop="checkerId" label="审核人" />
        <el-table-column align="center" prop="checkTime" label="审核日期" />
        <el-table-column align="center" prop="quantity" label="盈亏数量" />
        <el-table-column align="center" prop="amount" label="成本价" />
      </el-table>

      <div style="padding: 20px 20px 0; color: #fdc31d">盘点明细</div>
      <hr style="border: 1px solid #e4e7ed" />
      <el-tabs v-model="activeName" class="demo-tabs">
        <!-- 基础信息 -->
        <el-tab-pane v-for="item in stockDetailList" :label="item.label" :name="item.name" :key="item.name">
          <el-table border :data="item.list" style="width: 100%; height: 80%">
            <el-table-column align="center" prop="id" label="条码" width="250" />
            <el-table-column align="center" prop="name" label="名称" width="250" />
            <el-table-column align="center" prop="categoryName" label="商品分类" />
            <el-table-column align="center" prop="unitName" label="单位" />
            <el-table-column align="center" prop="realQuantity" label="实盘数量" />
            <el-table-column align="center" prop="planQuantity" label="账面数量" />
            <el-table-column align="center" prop="profitLossQuantity" label="盈亏数量" />
            <el-table-column align="center" prop="costPrice" label="成本价" />
            <el-table-column align="center" prop="profitLossAmount" label="盈亏金额" />
          </el-table>
        </el-tab-pane>

        <!-- <el-tab-pane label="盘平" name="second">
          <el-table border :data="tableData" style="width: 100%; height: 80%">
            <el-table-column align="center" prop="date" label="条码" width="250" />
            <el-table-column align="center" prop="name" label="名称" width="250" />
            <el-table-column align="center" prop="address" label="商品分类" />
            <el-table-column align="center" prop="address" label="单位" />
            <el-table-column align="center" prop="address" label="实盘数量" />
            <el-table-column align="center" prop="address" label="账面数量" />
            <el-table-column align="center" prop="address" label="盈亏数量" />
            <el-table-column align="center" prop="address" label="成本价" />
            <el-table-column align="center" prop="address" label="盈亏金额" />
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="盘盈" name="third">
          <el-table border :data="tableData" style="width: 100%; height: 80%">
            <el-table-column align="center" prop="date" label="条码" width="250" />
            <el-table-column align="center" prop="name" label="名称" width="250" />
            <el-table-column align="center" prop="address" label="商品分类" />
            <el-table-column align="center" prop="address" label="单位" />
            <el-table-column align="center" prop="address" label="实盘数量" />
            <el-table-column align="center" prop="address" label="账面数量" />
            <el-table-column align="center" prop="address" label="盈亏数量" />
            <el-table-column align="center" prop="address" label="成本价" />
            <el-table-column align="center" prop="address" label="盈亏金额" />
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="盘亏" name="fourth">
          <el-table border :data="tableData" style="width: 100%; height: 80%">
            <el-table-column align="center" prop="date" label="条码" width="250" />
            <el-table-column align="center" prop="name" label="名称" width="250" />
            <el-table-column align="center" prop="address" label="商品分类" />
            <el-table-column align="center" prop="address" label="单位" />
            <el-table-column align="center" prop="address" label="实盘数量" />
            <el-table-column align="center" prop="address" label="账面数量" />
            <el-table-column align="center" prop="address" label="盈亏数量" />
            <el-table-column align="center" prop="address" label="成本价" />
            <el-table-column align="center" prop="address" label="盈亏金额" />
          </el-table>
        </el-tab-pane> -->

        <!-- <el-tab-pane label="漏盘" name="fifth">
          <el-table border :data="tableData" style="width: 100%; height: 80%">
            <el-table-column align="center" prop="date" label="条码" width="250" />
            <el-table-column align="center" prop="name" label="名称" width="250" />
            <el-table-column align="center" prop="address" label="商品分类" />
            <el-table-column align="center" prop="address" label="单位" />
            <el-table-column align="center" prop="address" label="实盘数量" />
            <el-table-column align="center" prop="address" label="账面数量" />
            <el-table-column align="center" prop="address" label="盈亏数量" />
            <el-table-column align="center" prop="address" label="成本价" />
            <el-table-column align="center" prop="address" label="盈亏金额" />
          </el-table>
        </el-tab-pane> -->
        <!-- <el-tab-pane name="sixth">
          <template #label>
            <el-checkbox>漏盘商品清零</el-checkbox>
          </template>
        </el-tab-pane> -->
      </el-tabs>
    </div>
  </div>
</template>

<style lang="scss" scoped></style>
